package net.template.service;

import net.template.domain.template.Template;
import net.template.domain.template.TemplateAttr;
import net.template.domain.template.TemplateSimple;
import net.template.repository.TemplateRepository;
import net.template.service.controller.BaseController;
import net.template.service.controller.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.*;

/**
 * Created by Administrator on 2018/9/16/016.
 */
@RestController
@CrossOrigin
@RequestMapping("template")
public class TemplateService extends BaseController {
    @Autowired
    private TemplateRepository templateRepository;

    /**
     * 新增模板
     * @param input
     * @return
     */
    @Transactional
    @PostMapping
    public Result<Void> createTemplate(@RequestBody TemplateSimple input){
        Template template = new Template();
        template.createVerify(input);
        List<TemplateAttr> attrs = input.getReturnList();

        attrs.forEach(c->{
            //关键
            c.setTemplate(template);
        });
        templateRepository.save(template);
        return Result.success();
    }

    /**
     * 修改模板
     * @param input
     * @return
     */
    @Transactional
    @PutMapping("/{id}")
    public Result<Void> updateTemplate(@PathVariable("id") Integer id, @RequestBody TemplateSimple input){
        Template template = templateRepository.load(id);
        template.createVerify(input);
        List<TemplateAttr> attrs = input.getReturnList();
        attrs.forEach(c->{
            //关键
            c.setTemplate(template);
        });
        templateRepository.save(template);
        return Result.success();
    }

    @GetMapping
    public Result<List<Template>> queryTemplateList(){
        List<Template> templateList = templateRepository.findAll(new Specification<Template>() {
            @Override
            public Predicate toPredicate(Root<Template> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate = criteriaBuilder.isNotNull(root.get("id"));
                return predicate;
            }
        });

        return Result.success(templateList);
    }

    /**
     * 查询模板
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result<Template> queryTemplate(@PathVariable("id") Integer id){
        Template template = templateRepository.load(id);
        return Result.success(template);
    }
}
